import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_class2/3681/accountRelated/account_controller.dart';
import 'package:toast/toast.dart';

class CAPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => CAPageState();
}

class CAPageState extends State<CAPage> {
  //手机号的控制器
  TextEditingController phoneController = new TextEditingController();

  //密码的控制器
  TextEditingController passController = TextEditingController();

  //用户名的控制器
  TextEditingController usernameController = new TextEditingController();

  //第二次输入密码的控制器
  TextEditingController repassController = TextEditingController();

  //邮箱的控制器
  TextEditingController emilController = new TextEditingController();

  var accountDatabaseHelper = new AccountDatabaseHelper();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      appBar: AppBar(
        title: Text('注册页面'),
      ),
      body: Column(
        children: <Widget>[
          Image.asset(
            'images/ccb.png',
            width: 200,
            height: 100,
          ),
          TextField(
            controller: usernameController,
            keyboardType: TextInputType.url,
            inputFormatters: [
              LengthLimitingTextInputFormatter(8),
            ],
            decoration: InputDecoration(
              //decoration参数接收一个InputDecoration类型的值
              contentPadding: EdgeInsets.all(10.0), //内间距
              icon: Icon(Icons.supervised_user_circle),
              labelText: '请创建你的用户名(1~8位)',
            ),
            autofocus: false,
          ),
          TextField(
            controller: phoneController,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              //decoration参数接收一个InputDecoration类型的值
              contentPadding: EdgeInsets.all(10.0), //内间距
              icon: Icon(Icons.phone),
              labelText: '请输入你的手机号',
            ),
            autofocus: false,
          ),
          TextField(
            controller: emilController,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              //decoration参数接收一个InputDecoration类型的值
              contentPadding: EdgeInsets.all(10.0), //内间距
              icon: Icon(Icons.mail),
              labelText: '请输入邮箱',
            ),
            autofocus: false,
          ),
          TextField(
              controller: passController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.lock),
                labelText: '请输入密码(最低6位)',
              ),
              obscureText: true),
          TextField(
              controller: repassController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.lock_outlined),
                labelText: '请再次输入密码',
              ),
              obscureText: true),
          RaisedButton(
            color: Colors.blue,
            textColor: Colors.white,
            onPressed: _login,
            child: Text('注册'),
          ),
        ],
      ),
    );
  }

  void _login() async {
    print({
      'phone': phoneController.text,
      'password': passController.text,
      'username': usernameController.text,
      'emil': emilController.text,
      'repassword': repassController.text
    });

    if (await accountDatabaseHelper.getAccount(usernameController.text) != null) {
      print(accountDatabaseHelper.getCount());
      Toast.show('当前用户名已存在，请更改用户名', context);
    } else {
      if (usernameController.text.length >= 1) {
        // 判断用户名是否合理
        if (passController.text.length >= 6) {
          // 判断密码是否合理
          if (phoneController.text.length != 0) {
            // 若手机号、邮箱一栏不为空，则判断其格式是否正确
            if (isChinaPhoneLegal(phoneController.text)) {
              if (emilController.text.length != 0) {
                if (passController.text == repassController.text) {
                  if (isEmailLegal(emilController.text)) {
                    Toast.show('注册成功', context);
                    successAccountCCB(
                      accountDatabaseHelper,
                      usernameController.text.toString(),
                      passController.text.toString(),
                      phoneController.text.toString(),
                      emilController.text.toString(),
                    );
                    Navigator.pop(context);
                  } else {
                    showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                              title: Text('邮箱有误!'),
                            ));
                  }
                } else {
                  showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                            title: Text('两次输入密码不同!'),
                          ));
                }
              }
            } else {
              Toast.show('手机号有误', context);
            }
          }
        } else {
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                    title: Text('密码过短!'),
                  ));
        }
      } else {
        showDialog(
            context: context,
            builder: (context) => AlertDialog(
                  title: Text('用户名长度过短!'),
                ));
      }
    }
    ;
  }

  ///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
  /// 此方法中前三位格式有： 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
  bool isChinaPhoneLegal(String str) {
    return new RegExp(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }

  /// 检查是否是邮箱格式
  bool isEmailLegal(String input) {
    if (input == null || input.isEmpty) return false;
    return new RegExp("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$")
        .hasMatch(input);
  }

  Future<void> successAccountCCB(
      AccountDatabaseHelper db, columnId, password, phoneNum, email) async {
    await db.saveAccount(new Account(
        columnId, password, phoneNum, email, ' ', ' ', 0, 0, 0, ' ', ' '));
  }
}
